package org.spiderflow.core.utils;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * 文件处理工具类
 *
 * @author ruoyi
 */
public class FileUtils {
    private static final Logger logger = LoggerFactory.getLogger(FileUtils.class);

    public static final String FILENAME_PATTERN = "[a-zA-Z0-9_\\-|.\\u4e00-\\u9fa5]+";

    private FileUtils() {
    }

    /**
     * 输出指定文件的byte数组
     *
     * @param filePath 文件路径
     * @param os       输出流
     * @return
     */
    public static void writeBytes(String filePath, OutputStream os) throws IOException {
        File file = new File(filePath);
        if (!file.exists()) {
            throw new FileNotFoundException(filePath);
        }
        try (FileInputStream fis = new FileInputStream(file)) {
            byte[] b = new byte[1024];
            int length;
            while ((length = fis.read(b)) > 0) {
                os.write(b, 0, length);
            }
        } finally {
            if (os != null) {
                os.close();
            }
        }
    }

    /**
     * 删除文件
     *
     * @param filePath 文件
     * @return
     */
    public static boolean deleteFile(String filePath) {
        boolean flag = false;
        File file = new File(filePath);
        // 路径为文件且不为空则进行删除
        if (file.isFile() && file.exists() && fileDelete(file)) {
            flag = true;
        }
        return flag;
    }

    /**
     * 文件名称验证
     *
     * @param filename 文件名称
     * @return true 正常 false 非法
     */
    public static boolean isValidFilename(String filename) {
        return filename.matches(FILENAME_PATTERN);
    }

    /**
     * 下载文件名重新编码
     *
     * @param request  请求对象
     * @param fileName 文件名
     * @return 编码后的文件名
     */
    public static String setFileDownloadHeader(HttpServletRequest request, String fileName)
            throws UnsupportedEncodingException {
        final String agent = request.getHeader("USER-AGENT");
        String filename = fileName;
        if (agent.contains("MSIE")) {
            // IE浏览器
            filename = URLEncoder.encode(filename, StandardCharsets.UTF_8.name());
            filename = filename.replace("+", " ");
        } else if (agent.contains("Firefox")) {
            // 火狐浏览器
            filename = new String(fileName.getBytes(), StandardCharsets.ISO_8859_1);
        } else if (agent.contains("Chrome")) {
            // google浏览器
            filename = URLEncoder.encode(filename, StandardCharsets.UTF_8.name());
        } else {
            // 其它浏览器
            filename = URLEncoder.encode(filename, StandardCharsets.UTF_8.name());
        }
        return filename;
    }


    public static void downloadFile(String savePath, String fileUrl, boolean downNew) {
        if (StringUtils.isBlank(fileUrl)) {
            logger.error("下载失败,URL为空");
            return;
        }
        String fileName;
        URL urlFile;
        try {
            String url = fileUrl.startsWith("//") ? "http:" + fileUrl : fileUrl;
            urlFile = new URL(url);
            String urlPath = urlFile.getPath();
            fileName = urlPath.substring(urlPath.lastIndexOf("/") + 1);
        } catch (MalformedURLException e) {
            logger.error("URL异常", e);
            return;
        }
        File save = new File(savePath);
        if (!save.exists() && !save.mkdirs()) {
            logger.error("文件夹创建失败 path->{}", savePath);
            return;
        }
        String path = savePath + File.separator + fileName;
        File file = buildFile(downNew, path);
        if (file == null) {
            return;
        }
        downloadToFile(urlFile, file);
    }

    private static File buildFile(boolean downNew, String path) {
        File file = new File(path);
        if (file.exists()) {
            if (!downNew) {
                logger.info("文件已存在不重新下载！");
                return null;
            }
            fileDelete(file);
        }
        return file;
    }

    private static boolean fileDelete(File file) {
        try {
            Files.deleteIfExists(Paths.get(file.getPath()));
            return true;
        } catch (IOException e) {
            logger.error("文件删除失败！");
        }
        return false;
    }

    private static void downloadToFile(URL urlFile, File file) {
        HttpURLConnection httpUrl = getHttpUrlConnection(urlFile);
        if (httpUrl == null) {
            return;
        }
        try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
             BufferedInputStream bis = new BufferedInputStream(httpUrl.getInputStream())) {
            int len = 2048;
            byte[] b = new byte[len];
            while ((len = bis.read(b)) != -1) {
                bos.write(b, 0, len);
            }
            logger.info("远程文件下载成功:{}", urlFile.getPath());
            bos.flush();
            httpUrl.disconnect();
        } catch (IOException | RuntimeException e) {
            logger.error("远程文件下载失败", e);
        }
    }

    private static HttpURLConnection getHttpUrlConnection(URL urlFile) {
        try {
            HttpURLConnection httpUrl = (HttpURLConnection) urlFile.openConnection();
            httpUrl.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:68.0) Gecko/20100101 Firefox/68.0");
            //读取超时时间
            httpUrl.setReadTimeout(60000);
            //连接超时时间
            httpUrl.setConnectTimeout(60000);
            httpUrl.connect();
            return httpUrl;
        } catch (SocketTimeoutException e) {
            logger.error("Url读取超时 ->{}", urlFile.getPath(), e);
        } catch (IOException e) {
            logger.error("Url连接失败 ->{}", urlFile.getPath(), e);
        }
        return null;
    }
}
